package com.cqust.service;

import com.cqust.mapper.EmployeeMapper;
import com.cqust.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService{
    @Autowired
    private EmployeeMapper employeeMapper;

    public List<Employee> getEmployees() {
        return employeeMapper.getEmployees();
    }

    public Employee getEmployee(String id) {
        return employeeMapper.getEmployee(id);
    }

    public void addEmployee(Employee employee, HttpSession session) {
        MultipartFile img = employee.getImg();
        String filename = img.getOriginalFilename();
        ServletContext servletContext = session.getServletContext();
        String realPath = servletContext.getRealPath("static/img");
        String imgPath =realPath + File.separator + filename;
        try {
            img.transferTo(new File(imgPath));
            employee.setPhoto(filename);
            employeeMapper.addEmployee(employee);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void deleteEmployee(String id) {
        employeeMapper.deleteEmployee(id);
    }

    public void updateEmployee(Employee employee,HttpSession session) {
        MultipartFile img = employee.getImg();
        if(img.getSize()!=0) {
            String photo  = System.currentTimeMillis()+".jpg";
            ServletContext servletContext = session.getServletContext();
            String realPath = servletContext.getRealPath("static/img");
            String imgPath = realPath + File.separator + photo;
            try {
                img.transferTo(new File(imgPath));
                employee.setPhoto(photo);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        employeeMapper.updateEmployee(employee);
    }

    public List<Employee> getEmployeeLike(String name, String department) {
        name = "%"+name+"%";
        department = "%"+department+"%";
        return employeeMapper.getEmployeeLike(name,department);
    }
}
